package com.mytest.provider.service.config.security;


import com.mytest.provider.service.config.security.jwt.AuthenticationFailHandler;
import com.mytest.provider.service.exception.ValidateCodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fengjie
 * 写完该类，需要将此类加到SecurityConfig配置类中。
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter {


    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 认证失败处理
     */
    @Autowired
    private AuthenticationFailHandler failHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //所有要拦截的需要验证码验证的路径，可以设置成可配置的
        //TODO retailStore
        String[] urls = {"/login","/authentication/mobile"};
        boolean isTrue = false;
        String requestURI = request.getRequestURI();
        for (String url : urls){
            //判断当前路径是不是需要验证码验证的路径
            if (StringUtils.equals(url,requestURI)){
                isTrue = true;
                break;
            }
        }
        if(isTrue){
            try {
                validate(request);
            } catch (AuthenticationException e) {
                //调用自己定义的登录失败处理器进行处理。
                failHandler.onAuthenticationFailure(request,response,e);
                //出错返回，不向下执行
                return;
            }
        }
        //如果不符合以上的要求或验证通过，则调用下一个过滤器
        filterChain.doFilter(request,response);
    }



    private void validate(HttpServletRequest request) throws AuthenticationException {
        //获取前台传过来的验证码
        //验证码ID
        String captchaId = request.getParameter("captchaId");
        String code = request.getParameter("code");
        //前台输入的验证码
        if(StringUtils.isBlank(code)) {
            throw new ValidateCodeException("验证码不能为空");
        }

        //存放到缓存的验证码
        String codeCache = (String)redisTemplate.opsForValue().get(captchaId);
        if (StringUtils.isEmpty(captchaId)){
            throw new ValidateCodeException("验证码已过期");
        }

        //校验验证码，不区分大小写
        if(!StringUtils.equalsIgnoreCase(codeCache,code)){
            throw new ValidateCodeException("验证码错误");
        }
    }
}
